package com.xwdeshj.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xwdeshj.entity.XwCrowd;
import com.xwdeshj.entity.XwSceincThemetype;
import com.xwdeshj.repository.XwCrowdRepository;
import com.xwdeshj.service.XwCrowdService;
import com.xwdeshj.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by BKWJA on 2018/12/21.
 * 农家乐，景区适合人群类型接口层
 */
@Slf4j
@Service("xwCrowdService")
public class XwCrowdServiceImpl implements XwCrowdService {

    @Autowired
    private XwCrowdRepository xwCrowdRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private Sid sid;

    @Override
    public JSONObject getAllCrowd() {
        JSONObject result = new JSONObject();
        String sql = "select scenic_crowd_Id,crowd_encryptId,crowd_desc from xw_crowd order by crowd_createtime ASC";
        try {
            SqlRowSet rs = jdbcTemplate.queryForRowSet(sql);
            JSONArray jsonArray = new JSONArray();
            while (rs.next()){
                JSONObject object = new JSONObject();
                object.put("CrowdId",rs.getString("scenic_crowd_Id"));
                object.put("encryptId",rs.getString("crowd_encryptId"));
                object.put("title",(rs.getString("crowd_desc")==null?"":rs.getString("crowd_desc")));
                jsonArray.add(object);
            }
            result.put("list",jsonArray);
            result.put("status",0);
            result.put("msg","ok");
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg",e);
        }
        System.out.println("getAllfarmMertype："+result.toString());
        return  result;
    }

    @Override
    public JSONObject getCrowdlist(Integer pageindex, Integer pagesize, String starttime,
                                   String endtime, String sortfild, String sortway) {
        JSONObject result = new JSONObject();
        String sql = "select scenic_crowd_Id,crowd_encryptId,crowd_desc,crowd_updatetime,crowd_createtime from xw_crowd ";
        StringBuffer sb = new StringBuffer();
        sb.append(" 1=1 ");
        if(!starttime.equals("")){
            starttime += " 00.00.01";
            endtime += " 23.59.59";
            sb.append(" and crowd_createtime >= '"+starttime+"' and crowd_createtime <= '"+ endtime + "' ");
        }
        //排序
        if (!sortfild.equals("")){
            sb.append(" order by "+sortfild+" " +sortway + " ");
        }
        try {
            sql = sql + " where " +sb.toString() + " limit "+ (pageindex-1)*pagesize + "," + pagesize;
            //分页SQL
            String sql2 = "select count(*) from xw_crowd where " + sb.toString();
            SqlRowSet rs = jdbcTemplate.queryForRowSet(sql);
            SqlRowSet rs2 = jdbcTemplate.queryForRowSet(sql2);
            result.put("status",0);
            result.put("msg","ok");
            while (rs2.next()){
                Integer count = rs2.getInt(1);
                result.put("recordcount",count);
                if (count%pagesize == 0){
                    result.put("pagecount",count/pagesize);
                }else {
                    result.put("pagecount",count/pagesize + 1);
                }
            }
            JSONArray jsonArray = new JSONArray();
            while (rs.next()){
                JSONObject object = new JSONObject();
                object.put("scenic_crowd_Id",rs.getString("scenic_crowd_Id"));
                object.put("crowd_encryptId",rs.getString("crowd_encryptId"));
                object.put("crowd_desc",(rs.getString("crowd_desc")==null?"":rs.getString("crowd_desc")));
                object.put("crowd_updatetime", DateUtil.DateToString(rs.getDate("crowd_updatetime")));
                object.put("crowd_createtime",DateUtil.DateToString(rs.getDate("crowd_createtime")));
                jsonArray.add(object);
            }
            result.put("list",jsonArray);
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg",e);
        }
        System.out.println("getCrowdlist:"+result.toString());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject updateCrowdinfo(String crowd_encryptId, String crowd_desc) {
        JSONObject result = new JSONObject();
        if(crowd_encryptId.equals("")){
            XwCrowd crowd = new XwCrowd();
            crowd.setCrowdEncryptid(sid.nextShort());
            crowd.setCrowdDesc(crowd_desc);
            crowd.setCrowdCreatetime(new Date());
            crowd.setCrowdUpdatetime(new Date());

            try {
                xwCrowdRepository.save(crowd);
                result.put("status",0);
                result.put("msg","ok");
            }catch (Exception e){
                e.printStackTrace();
                result.put("status",500);
                result.put("msg",e);
            }
        }else {
            XwCrowd xwCrowd = xwCrowdRepository.findByCrowdEncryptid(crowd_encryptId);

            if (xwCrowd != null){
                xwCrowd.setCrowdDesc(crowd_desc);
                xwCrowd.setCrowdUpdatetime(new Date());
                try {
                    xwCrowdRepository.save(xwCrowd);
                    result.put("status",0);
                    result.put("msg","ok");
                }catch (Exception e){
                    e.printStackTrace();
                    result.put("status",500);
                    result.put("msg",e);
                }
            }else {
                result.put("status",500);
                result.put("msg","该记录不存在！");
            }

        }
        System.out.println("updateCrowdinfo:"+result.toString());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject delCrowdinfo(String crowd_encryptId) {
        JSONObject result = new JSONObject();
        if(!"".equals(crowd_encryptId) && crowd_encryptId != null){
            try {
                if(crowd_encryptId.indexOf(",") == -1){
                    //单个删除
                    int flag =  xwCrowdRepository.deleteByCrowdEncryptid(crowd_encryptId);
                    if(flag == 1){
                        result.put("status",0);
                        result.put("msg","ok");
                    }else {
                        result.put("status",500);
                        result.put("msg","删除失败！");
                    }
                }else {
                    //批量删除
                    int flag = 0;
                    String[] tids = crowd_encryptId.split(",");
                    for (int i = 0; i < tids.length; i++) {
                        flag = xwCrowdRepository.deleteByCrowdEncryptid(tids[i]);
                    }
                    if(flag == 1){
                        result.put("status",0);
                        result.put("msg","ok");
                    }else {
                        result.put("status",500);
                        result.put("msg","删除失败！");
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                result.put("status",500);
                result.put("msg",e);
            }

        }else {
            result.put("status",500);
            result.put("msg","crowd_encryptId不能为空！");
        }
        System.out.println("delCrowdinfo："+result);
        return result;
    }
}
